import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import { authRoutes } from '../router';//引入所有路由表，待筛选
Vue.use(Vuex);
const getRoutes = (authList) => {
  // authRoutes所有路由，authList获取的权限
  //过滤出添加的路由
  let auths = authList.map(item => item.auth);
  const filter = (authRoutes) => {
    let result = authRoutes.filter(route => {
      if (auths.includes(route.name)) {
        if (route.children) {
          route.children = filter(route.children)//filter递归过滤，有就返回
        }
        return route;
      }
    })
    return result
  }
  let r = filter(authRoutes)
  return r
}
export default new Vuex.Store({
  state: {
    hasPermission: false,//第一次加载页面时，获取权限，之后再切换时就不用获取权限了
    authList: [],        //权限列表
    btnPermission: {     //模拟按钮权限
      edit: true,
      add: false
    }
  },
  mutations: {
    setPermission(state) {
      state.hasPermission = true;
    },
    setAuthList(state, list) {
      state.authList = list;
    }
  },
  actions: {
    async getMenuList(store) {
      let { data } = await axios.get('http://localhost:3000/category')
      let r = data.menuList.map(item => ({ name: item.name, auth: item.auth, id: item.id }))
      store.commit('setAuthList', r)
      store.commit('setPermission')//此时设置好权限了
      return r;
    },
    async getAuthRouter(store) {// action可以调用另一个action
      //获取菜单列表
      let authList = await store.dispatch('getMenuList')
      //需要通过权限路由，筛选出当前需要用到的路由，动态的添加进去
      return getRoutes(authList)
    }
  }
})